/**
 * 固定高度虚拟滚动
 * 1、滚动范围高度计算
 * 2、上缓冲区域起始下标
 * 3、可视区域起始下标
 * 4、下缓冲区域结束下标
 * 5、替换数据
 */
import { ref, onMounted, onUnmounted } from "vue";
import { FixedOptions } from "@table/interface";

export const useFixedVirtual = (options: FixedOptions) => {
  const fixedVirtualData = ref([]);

  const { contain, height, bufferNumber, wrap, data, offsetTop } = options;

  let viewNumber = 0;
  const initFixedVirtual = () => {
    viewNumber = Math.ceil(wrap.value.clientHeight / height);
    // 设置容器高度
    contain.value.style.setProperty("height", `${data.value.length * height}px`);
    renderData();
    wrap.value.addEventListener("scroll", renderData);
  };
  const renderData = () => {
    // 可视区域的开始索引下标
    const viewStartIndex = Math.floor((wrap.value.scrollTop + (offsetTop || 0)) / height);
    // 上缓冲区开始的索引下标
    const bufferStartIndex = Math.max(0, viewStartIndex - bufferNumber);
    // 下缓冲区结束的索引下标
    const bufferEndIndex = Math.min(data.value.length - 1, viewStartIndex + viewNumber + bufferNumber);
    console.log(bufferStartIndex, bufferEndIndex);
    fixedVirtualData.value = data.value.slice(bufferStartIndex, bufferEndIndex + 1).map((item, index) => {
      return {
        ...item,
        top: (index + bufferStartIndex) * height
      };
    });
  };

  onUnmounted(() => {
    wrap.value.removeEventListener("scroll", renderData);
  });
  onMounted(() => {
    initFixedVirtual();
  });

  return {
    fixedVirtualData
  };
};
